import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { tableList, tableListDelete } from '../../services/login';
import SearchAndSheet from './components/SearchAndSheet';
import TableRendering from './components/TableRendering';
import { Card, Tabs, Form, Button, DatePicker, message } from 'antd';
import { history } from 'umi';
import './index.css';

// *-------------------------------------
export default () => {
  // todo 这是 tab 栏的固定数据
  const [tabsList, setTabsList] = useState([
    { tab: '全部', key: '0' },
    { tab: '进行中', key: '2' },
    { tab: '未开始', key: '3' },
    { tab: '已结束', key: '5' },
    { tab: '待审核', key: '1' },
    { tab: '已驳回', key: '4' },
    { tab: '草稿箱', key: '7' },
  ]);

  // todo 这是 tab 栏切换
  const { TabPane } = Tabs;
  const [draftBox, setDraftBox] = useState('');
  const [tabActivityStatus, setTabActivityStatus] = useState([]);
  const [tabChosen, setTabChosen] = useState('');
  const callback = async (e) => {
    setFormTime([]);
    setFormValue('');
    form.resetFields();
    setDraftBox('');
    setTabActivityStatus([]);
    const num = parseInt(e);
    if (num !== 0) {
      if (num == 5 || num == 6) {
        setTabActivityStatus([5]);
        const { data } = await tableList({ activityStatus: [5, 6] });
        // console.log(data);
        setTotal(data.total);
        setList(data.rows);
      } else if (num == 7) {
        // setTabActivityStatus([5]);
        setDraftBox(1);
        const { data } = await tableList({ isDraft: 1 });
        // console.log(data);
        setTotal(data.total);
        setList(data.rows);
      } else {
        setDraftBox('');
        setTabActivityStatus([num]);
        const { data } = await tableList({ activityStatus: [num] });
        // console.log(data);
        setTotal(data.total);
        setList(data.rows);
      }
    } else {
      setDraftBox('');
      setTabActivityStatus([]);
      const { data } = await tableList({});
      // console.log(data);
      setTotal(data.total);
      setList(data.rows);
    }
    setPageOption({
      pageNo: 1,
      pageSize: 10,
    });
  };

  // *------------------------------------
  // todo 请求的 tableList 数据
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  useEffect(() => {
    tableList({}).then((res) => {
      // console.log(res.data);
      try {
        setList(res.data.rows);
        setTotal(res.data.total);
      } catch {
        message.warning('获取信息失败，请刷新重试');
      }
    });
  }, []);

  // todo 这是删除后的刷新
  const AfterDeleting = async (record) => {
    const data = await tableListDelete({ activityBasicIds: [record.activityBasicId] });
    if (data.code == 200) {
      tableList({
        isDraft: draftBox,
        activityStatus: tabActivityStatus,
        activityName: formValue,
        queryStartDate: formTime[0],
        queryEndDate: formTime[1],
        page: pageOption.pageNo,
        pageSize: pageOption.pageSize,
      }).then((res) => {
        // console.log(res.data);
        try {
          setList(res.data.rows);
          setTotal(res.data.total);
        } catch {
          message.warning('获取信息失败，请刷新重试');
        }
      });
      message.success('删除成功');
    }
  };

  // *------------------------------------------
  // todo 这是分页的数据控制
  const [pageOption, setPageOption] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  // todo 显示的数据
  const paginationProps = {
    showQuickJumper: true,
    showTotal: () => `共${total}条`,
    total: total,
    current: pageOption.pageNo,
    pageSize: pageOption.pageSize,
    onChange: (current, size) => paginationChange(current, size),
  };
  // todo 分页的change事件
  const paginationChange = async (current, size) => {
    // console.log('page', current, size);
    console.log(formTime);
    setPageOption({
      pageNo: current,
      pageSize: size,
    });
    const { data } = await tableList({
      isDraft: draftBox,
      activityStatus: tabActivityStatus,
      activityName: formValue,
      queryStartDate: formTime?.[0],
      queryEndDate: formTime?.[1],
      page: current,
      pageSize: size,
    });
    // console.log(data);
    setTotal(data.total);
    setList(data.rows);
  };

  // *------------------------------------------
  // todo 表单提交
  //todo 这是From表单的数据
  const [timerFlag, setTimerFlag] = useState(true);
  let timer = null;
  // const throttling = () => {};
  const [formTime, setFormTime] = useState([]);
  const [formValue, setFormValue] = useState('');
  const [form] = Form.useForm();
  const onFinish = async (values) => {
    const timeFormat = values.formCreationTime?.map((item) => {
      return item.format('YYYY-MM-DD HH:mm');
    });
    timeFormat ? setFormTime(timeFormat) : setFormTime([]);
    setFormValue(values.formActivityName);
    const { data } = await tableList({
      activityStatus: tabActivityStatus,
      activityName: values.formActivityName,
      queryStartDate: timeFormat?.[0],
      queryEndDate: timeFormat?.[1],
      isDraft: draftBox,
      // page: current,
      // pageSize: size,
    });
    // console.log(data);
    setTotal(data.total);
    setList(data.rows);
    setPageOption({
      pageNo: 1,
      pageSize: 10,
    });
  };

  // todo 重置按钮
  const formReset = () => {
    setFormTime([]);
    setFormValue('');
    form.resetFields();
  };

  //*--------------------------------------------
  // todo 跳转到创建新活动页面的按钮
  const createNewEvent = () => {
    history.push('/createNewEvent');
  };

  // *-------------------------------------------
  // ! 这是虚拟 DOM
  return (
    <PageContainer title={false}>
      <Card>
        <p className="title">创建活动</p>
        {/* 这是 tab 栏  */}
        <Tabs
          defaultActiveKey={tabChosen}
          onChange={(e) => {
            callback(e);
          }}
        >
          {tabsList.map((item) => (
            <TabPane tab={item.tab} key={item.key}>
              {/* 活动提交表单 */}
              <SearchAndSheet form={form} onFinish={onFinish} formReset={formReset} />
              {/* 活动提交表单 结束*/}
              <Button className="createEvent" onClick={createNewEvent}>
                + 创建活动
              </Button>
              {/* 表单 */}
              <TableRendering
                list={list}
                total1={total}
                paginationProps={paginationProps}
                AfterDeleting={AfterDeleting}
              />
              {/* 表单 结束*/}
            </TabPane>
          ))}
        </Tabs>
        {/* 这是 tab 栏 结束  */}
      </Card>
    </PageContainer>
  );
};
